<template>
  <div id="d-homePage" class="d-homePage" :style="{minHeight: minHeight}">
    <div v-show="showSearch">
      <div>
        <van-search
          placeholder="请输入搜索关键词"
          show-action
          v-model="value"
          @cancel="returnHomePage"
          @search="onSearch"
          class="needsclick"
          @blur="setBMH"
          @click="setFMH"
        >
          <div slot="action" @click="onSearch" v-if="cancelValue">搜索</div>
          <div slot="action" @click="returnHomePage" v-else>取消</div>
        </van-search>
        <div class="searchHistory" v-if="showHistory">
          <div class="title">
            <span>历史记录</span>
            <img
              src="../../../assets/img/designer/homePage/clear@2x.png"
              alt
              @click="delteHistory()"
            />
          </div>
          <div class="content">
            <van-row gutter="20">
              <van-col span="8" v-for="(item,index) in historyList" :key="index">
                <div class="btn" v-if="index < 6" @click="followHistory(item)">
                  <span>{{item}}</span>
                </div>
              </van-col>
            </van-row>
          </div>
        </div>
        <div class="img-layout" v-if="showNoFindPhoto">
          <img src="../../../assets/img/designer/homePage/Bitmap@2x.png" alt />
          <p>找不到你要的结果</p>
        </div>
      </div>
    </div>
    <div v-show="!showSearch">
      <headerDiv
        @nearest="nearest"
        @location="location"
        @priceSort="priceSort"
        @evalution="evalution"
        @filter="filter"
        @caps="caps"
        @controlShowSearch="controlShowSearch"
        @maxHeight="maxHeight"
        @reset="reset"
        @setFMH="setFMH"
        @setBMH="setBMH"
        @resetFilter="resetFilter"
      ></headerDiv>
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <van-list
          v-if="!noNetword || list.length == 0"
          v-model="loading"
          :finished="finished"
          finished-text="提示：更多表现师不在您的区域内"
          @load="onLoad"
        >
          <card
            :cardList="list"
            :minHeight="'2.7rem'"
            @getUserInfo="getStatus"
            @insertBlackList="onClickAsyncClose"
          />
          <div class="nonetwork" v-if="noNetword || list.length == 0">
            <div>
              <img class="netWordErrorImg" src="../../../assets/img/public/nophone.png" alt />
              <p>暂无数据</p>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
      <main-nav></main-nav>
      <!-- <van-popup v-model="showLocation">
        <p>获取您的定位信息失败,请打开“定位服务”来允许“高德地图”确定您的定位，以下是深圳地区表现师信息11111111111111111111111111</p>
      </van-popup>-->

      <!-- <van-image-preview
        v-model="show"
        :images="imgGroup"
        :start-position="startPosition"
      ></van-image-preview>-->
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import { Dialog } from "vant";
Vue.use(Dialog);
import mainNav from "@/components/designer/mainNav";
import headerDiv from "@/components/designer/homePage/header";
import card from "@/components/designer/homePage/card";
import {
  setVersionNo,
  getToken,
  getuserUid,
  getPassword,
  setUserInfo
} from "@/utils/auth.js";
import { getVoice } from "@/utils/chat.js";
import { AMAPKEY, asyncLoadAMAP, Getsite } from "@/utils/amap.js";
import { mapState, mapMutations } from "vuex";
export default {
  name: "designerHomepage",
  components: {
    mainNav,
    headerDiv,
    card
  },
  data() {
    return {
      isLoading: false,
      list: [],
      searchInfo: {
        searchInput: "",
        //根据地点查询的UID
        areaUid: "",
        //beginPrice：根据最低价格区间筛选
        //endPrice：根据最高价格区间筛选
        searchPrice: {
          priceSortType: "",
          beginPrice: "",
          endPrice: ""
        },
        //顶部搜索(根据表现师名称)
        searchStr: ""
      },
      queryType: 0,
      areasType: "",
      selectType: "",
      filiter: {
        uidList: [],
        getDay: [],
        styleUid: []
      },
      capsUid: [],
      showSearch: false,
      value: "",
      historyList: [],
      cancelValue: false,
      showHistory: false,
      showNoFindPhoto: false,
      newVersionNo: "", // 新版本号
      downUrl: "", // 旧版本返回更新版本地址
      controlMaxHright: false,
      noNetword: false,
      pageNum: 0,
      pageSize: 10,
      loading: false,
      finished: false,
      latitude: "",
      longitude: "",
      center: [],
      dialogContent: "是否三天内不看他/她",
      imgGroup: [],
      show: false,
      startPosition: 0,
      minHeight: "100%"
      // showLocation: false
    };
  },
  watch: {
    //控制输入框右侧文字
    value(newVal) {
      if (newVal) {
        this.cancelValue = true;
      } else {
        this.cancelValue = false;
      }
    },
    historyList(newVal) {
      let history = window.localStorage.getItem("historyList");
      if (history) {
        this.showHistory = true;
      } else if (
        this.historyList == [] ||
        this.historyList == "" ||
        this.historyList == null
      ) {
        this.showHistory = false;
      }
    },
    list(newVal) {
      if (newVal.length == 0) {
        this.showNoFindPhoto = true;
      }
    },
    controlMaxHright(newVal) {
      let a = document.getElementsByClassName("van-pull-refresh")[0];
      if (newVal == true) {
        a.style.height = "100vh";
        // a.addEventListener("touchmove", function(event) {
        //   event.preventDefault();
        // });
      } else {
        a.style.height = "";
        // a.addEventListener("touchmove", function(e) {
        //   window.event.returnValue = true;
        // });
      }
    }
  },
  created() {
    // window.plus.webview.currentWebview().setStyle(
    //   {softinputMode: "adjustResize"}
    // );
    this.setTabIndex(0);
    this.getVersion();
    if (this.longitude != "" && this.latitude != "") {
      return;
    } else {
      this.getUserLocation();
    }
  },
  mounted() {
    //连接环信
    this.$imoption.user = getuserUid(); //环信账号
    this.$imoption.pwd = getPassword(); //环信密码
    this.$imconn.open(this.$imoption); //建立连接
    this.getUserInfo();
    if (this.historyList == [] || this.historyList == "") {
      this.showHistory = false;
    } else {
      this.showHistory = true;
    }
    this.value = "";
    if (this.longitude != "" && this.latitude != "") {
      return;
    } else {
      this.getUserLocation();
    }
  },
  destroyed() {
    if (this.$route.path != "/designer/homePage") {
      this;
    }
  },
  methods: {
    setBMH() {
      this.minHeight = "100vh";
    },
    setFMH() {
      this.minHeight = "130vh";
    },
    //异步弹框，选择不感兴趣的表现师拉黑
    onClickAsyncClose(val) {
      let _this = this;
      function beforeClose(action, done) {
        if (action === "confirm") {
          _this.insertBlackList(val);
          done();
        } else {
          done();
        }
      }
      this.$dialog
        .confirm({
          message: this.dialogContent,
          beforeClose
        })
        .catch(() => {});
    },
    //获取用户所在的定位
    getUserLocation() {
      asyncLoadAMAP();
      let _this = this;
      window.map_callback = async () => {
        let _center;
        try {
          _center = await Getsite();
          _this.longitude = _center[0];
          _this.latitude = _center[1];
          this.getBuser();
        } catch (error) {
          if (this.$route.path == "/designer/homePage") {
            this.$dialog
              .alert({
                message:
                  "获取您的定位信息失败,请打开“定位服务”来允许“图小助”确定您的位置，以下是深圳地区表现师信息"
              })
              .then(() => {
                // on close
              });
          }

          // this.showLocation = true;
          // _this.$toast(error);
          // alert(
          //   "获取您的定位信息失败,请打开“定位服务”来允许“高德地图”确定您的定位，以下是深圳地区表现师信息22222222222222222222"
          // );
          // _this.$toast(
          //   "获取您的定位信息失败,以下是深圳地区表现师信息333333333333333"
          // );
          _this.latitude = "22.551235";
          _this.longitude = "113.95483";
          _this.getBuser();
          return;
        }
      };
    },
    getStatus(val) {
      if (val == true) {
        this.getBuser();
      } else {
        return;
      }
    },
    //下拉刷新信息
    onRefresh() {
      setTimeout(() => {
        this.isLoading = false;
        this.getBuser();
      }, 500);
    },
    //存储用户信息userInfo
    getUserInfo() {
      HTTP("userCenter", {
        userUid: getuserUid()
      }).then(res => {
        if (res.code == 200) {
          setUserInfo(res.data);
        }
      });
    },
    //上滑添加数据
    onLoad() {
      setTimeout(() => {
        this.pageNum += 1;
        if (this.latitude !== "" && this.longitude !== "") {
          this.getBuser();
        }
        this.loading = false;
        this.finished = true;
      }, 500);
    },
    //距离最近查询
    nearest(val) {
      this.queryType = 1;
      this.areasType = 1;
      this.filiter = {};
      this.searchInfo.areaUid = "";
      this.getBuser();
    },
    //根据区域查询
    location(val) {
      this.queryType = 1;
      this.areasType = 2;
      this.filiter = {};
      this.searchInfo.areaUid = val.areaUid;
      this.getBuser();
    },
    //根据价格排序查询
    priceSort(val) {
      this.queryType = 2;
      this.areasType = "";
      this.searchInfo.areaUid = "";
      this.searchInfo.searchPrice.priceSortType = val.priceSortType;
      this.searchInfo.searchPrice.beginPrice = val.beginPrice;
      this.searchInfo.searchPrice.endPrice = val.endPrice;
      this.getBuser();
    },
    //根据评价查询
    evalution(val) {
      this.queryType = 3;
      this.selectType = val;
      this.searchInfo.searchPrice.priceSortType = "";
      this.searchInfo.searchPrice.beginPrice = "";
      this.searchInfo.searchPrice.endPrice = "";
      this.getBuser();
    },
    //添加筛选条件
    filter(val) {
      // this.filiter.uidList = [];
      // this.filiter.getDate = [];
      // this.filiter.styleUid = [];
      console.log(val);
      this.filiter = val;
      console.log(this.filiter);
      this.getBuser();
    },
    //根据技能信息查询
    caps(val) {
      this.capsUid = val;
      this.getBuser();
    },
    //从搜索页面返回首页重新查询数据
    returnHomePage() {
      this.showSearch = false;
      this.getBuser();
    },
    //根据缓存信息查询
    followHistory(item) {
      this.value = item;
      this.getBuser();
    },
    //根据输入的内容查询，并且将搜索条件存入localstorage
    onSearch() {
      let reg = /^[\u4E00-\u9FA5A-Za-z0-9]{1,10}$/;
      let temp = [];
      if (reg.test(this.value)) {
        this.getBuser();
        temp.push(this.value);
        for (let i = 0; i < temp.length; i++) {
          if (this.historyList.indexOf(temp[i]) == -1) {
            this.historyList.unshift(temp[i]);
          } else {
            this.historyList.unshift(temp[i]);
            let a = this.historyList.lastIndexOf(temp[i]);
            this.historyList.splice(a, 1);
          }
        }
        window.localStorage.setItem(
          "historyList",
          JSON.stringify(this.historyList)
        );
        setTimeout(() => {
          if (this.list.length == 0) {
            this.showNoFindPhoto = true;
            this.showSearch = true;
          } else {
            this.showNoFindPhoto = false;
            this.showSearch = false;
          }
        }, 100);
      } else {
        this.$toast("请输入合法的搜索值");
      }
      this.value = "";
    },
    //清除搜索记录
    delteHistory() {
      this.historyList = [];
      window.localStorage.removeItem("historyList");
      this.value = "";
      this.showHistory = false;
    },
    //控制需要展示的历史记录
    controlShowSearch(val) {
      this.historyList = [];
      this.value = "";
      this.showSearch = val;
      let history = window.localStorage.getItem("historyList");
      let a = JSON.parse(history);
      if (history) {
        this.showHistory = true;
        for (let i = 0; i < a.length; i++) {
          if (this.historyList.indexOf(a[i]) == -1) {
            this.historyList.push(a[i]);
          }
        }
      } else if (
        this.historyList == [] ||
        this.historyList == "" ||
        this.historyList == null
      ) {
        this.showHistory = false;
      }
    },
    //使遮罩层出现的时候让底部信息不能滑动
    maxHeight(val) {
      this.controlMaxHright = val;
    },
    //重置价格信息
    reset(val) {
      this.searchInfo.searchPrice.priceSortType = "";
      this.searchInfo.searchPrice.beginPrice = "";
      this.searchInfo.searchPrice.endPrice = "";
      this.queryType = 0;
      this.getBuser();
    },
    resetFilter(val) {
      this.filiter.uidList = [];
      this.filiter.getDay = [];
      this.filiter.styleUid = [];
      this.getBuser();
    },
    //获取表现师列表
    async getBuser() {
      console.log(this.filiter.getDate)
      try {
        const e = await HTTP("getbuser", {
          latitude: this.latitude,
          // latitude: 22,
          pageNum: this.pageNum,
          userUid: getuserUid(),
          longitude: this.longitude,
          // longitude: 113,
          pageSize: this.pageSize,
          queryType: this.queryType,
          areasType: this.areasType,
          selectType: this.selectType,
          priceSortType: this.searchInfo.searchPrice.priceSortType,
          beginPrice: this.searchInfo.searchPrice.beginPrice,
          endPrice: this.searchInfo.searchPrice.endPrice,
          areaUids: this.searchInfo.areaUid,
          skillList: this.capsUid,
          styleList: this.filiter.styleUid,
          typeList: this.filiter.uidList,
          dateList: this.filiter.getDay,
          searchStr: this.value
        });
        if (e.code === 200) {
          if (e.data.length > 0 && this.showSearch) {
            this.showSearch = false;
            if (!this.showSearch) {
              this.list = e.data;
            }
          } else {
            this.list = e.data;
          }
        }
      } catch (error) {
        this.noNetword = true;
      }
    },
    // 版本检测
    async getVersion() {
      const SPC = await HTTP("getVersion", {
        version: this.$v
      });
      if (SPC.code == 200) {
        if (SPC.data.version) {
          setVersionNo(SPC.data.version)
        } else {
          setVersionNo('1.0')
        }
        this.downUrl = SPC.data.downUrl;
        // this.downUrl = 'http://app.gongpaipai.com/pic/H54B04E4F_0531160120.apk'
        if (this.downUrl) {
          // 弹框立即下载
          Dialog.alert({
            title: "有新版本啦！",
            message: "更新更全功能，给您更好的使用体验",
            confirmButtonText: "立即升级"
          }).then(() => {
            this.jumpToAppMarket();
          });
        }
      } else {
        this.$toast(SPC.msg || "服务器异常");
      }
    },
    //跳转第三方应用平台
    jumpToAppMarket() {
      let _this = this;
      if (window.plus.os.name == "iOS") {
        location.href = 'https://apps.apple.com/cn/app/%E5%9B%BE%E5%B0%8F%E5%8A%A9-%E5%AE%A4%E5%86%85%E6%95%88%E6%9E%9C%E5%9B%BE%E4%B8%8A%E9%97%A8%E6%9C%8D%E5%8A%A1/id1471613155?from=singlemessage&isappinstalled=0';
        const toastI = _this.$toast.loading({
          duration: 3000, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          message: "上APP Store, 有最新版本哦~"
        });
        let secondI = 3;
        const timerI = setInterval(() => {
          secondI--;
          if (!secondI) {
            clearInterval(timerI);
            // _this.$toast.clear();
          }
        }, 3000);
      } else if (window.plus.os.name == "Android") {
		  location.href =  'https://a.app.qq.com/o/simple.jsp?pkgname=io.dcloud.H59C01B9C&from=singlemessage&isappinstalled=0'
      }
    },
    //拉黑表现师
    async insertBlackList(val) {
      try {
        const e = await HTTP(
          "app/attentionOrBlacklist/insertAttentionOrBlacklist",
          {
            type: 3,
            attentionUserUid: val.userUid,
            createBy: getuserUid()
          }
        );
        if (e.code === 200) {
          this.getBuser();
        } else {
          this.$toast("数据开小差了，请稍后再尝试");
        }
      } catch (error) {
        this.$toast("数据开小差了");
      }
    },
    // showPreview({ item, startPosition }) {
    //   this.startPosition = parseInt(startPosition);
    //   this.imgGroup = [];
    //   item.forEach(e => {
    //     this.imgGroup.push(e.shortImgUrl);
    //   });
    //   this.show = true;
    // },
    ...mapMutations(["setTabIndex"])
  }
};
</script>
<style lang="scss" scoped>
.d-homePage {
  background: #f9f9f9;
  .searchHistory {
    border-top: 0.01rem solid #e5e5e5;
    background: #ffffff;
    padding: 0.4rem 0.24rem;
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      img {
        width: 0.24rem;
        height: 0.28rem;
      }
      span {
        font-size: 0.28rem;
        font-weight: 400;
        color: #656565;
      }
    }
    .content {
      margin-top: 0.12rem;
      .btn {
        width: 2.18rem;
        height: 0.7rem;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 0.1rem;
        background: #f5f5f5;
        color: #282828;
        font-size: 0.28rem;
        font-weight: 400;
        margin: 0.12rem 0;
        span {
          width: 1.6rem;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          text-align: center;
        }
      }
    }
  }
  .img-layout {
    text-align: center;
    img {
      margin-top: 1rem;
      width: 3.74rem;
      height: 2.88rem;
    }
    p {
      font-size: 0.32rem;
      color: #959595;
      font-weight: 400;
      line-height: 0.32rem;
    }
  }
  .nonetwork {
    display: flex;
    justify-content: center;
    height: 100vh;
    > div:nth-child(1) {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 3rem;
      .netWordErrorImg {
        text-align: center;
        width: 3.8rem;
        height: 3rem;
      }
      p {
        color: #959595;
        font-size: 0.32rem;
        font-weight: 400;
      }
    }
  }
}
</style>

<style lang="scss">
.van-list {
  padding-bottom: 1rem !important;
}
</style>
